package xm.manager
{
	import com.greensock.TweenLite;
	import com.greensock.easing.Quint;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObjectContainer;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	
	import xm.components.ui.UIActionSheet;
	import xm.control.Navigator;
	import xm.control.bar.TabBar;
	import xm.events.UIEvent;
	import xm.interfaces.IUIActionManager;
	
	/**
	 * <br> 클래스 설명 : </br>
	 * @author 김정환
	 */	
	public class UIActionManager implements IUIActionManager
	{
		
		private static var _instance : IUIActionManager;
		

		/**
		 * @public
		 */
		public static function getInstance():IUIActionManager
		{
			if (!_instance)
				_instance = new UIActionManager( new singletonEnforce() );
			
			return _instance;
		}
		
		
		//-----------------------------------------------------------------------------------
		// public vars
		//-----------------------------------------------------------------------------------
		
		
		
		
		//-----------------------------------------------------------------------------------
		// protected / internal vars
		//-----------------------------------------------------------------------------------
		
		
		
		
		//-----------------------------------------------------------------------------------
		// private vars
		//-----------------------------------------------------------------------------------
		
		private var _modalWindow : Sprite;
		private var _uiActionSheet : UIActionSheet;
		private var _uiActionSheetBitmap : Bitmap;
		private var _dicAutoDestroy : Dictionary = new Dictionary( false );
		private var _isShow : Boolean = false;
		//-----------------------------------------------------------------------------------
		// public functions
		//-----------------------------------------------------------------------------------
		
		/**
		 * constructor 
		 */	
		public function UIActionManager( se : singletonEnforce )
		{
			if( se == null )
			{
				throw new Error( "싱글턴 객체이므로 생성이 불가합니다." );
			}
		}
		
		
		/**
		 * <br>페이지 하단에서 액션시트 나오게하는 기본메서드</br>
		 * @param uiActionSheet : UIActionSheet - 하단에서 등장할 액션 시트 객체.
		 * @param autoDestroy : Boolean - hide 될때 destroy 를 자동으로 처리할 지 여부.
		 */		
		public function showInView( uiActionSheet : UIActionSheet, autoDestroy : Boolean = false ):void
		{
			_isShow = true;
			
			_uiActionSheet = uiActionSheet;
			_dicAutoDestroy[ _uiActionSheet ] = autoDestroy;
			
			var s : Stage = StageManager.getInstance().stage,
				targetY : Number,
				tabBar : TabBar;
				
			
			var uiEvent : UIEvent = new UIEvent( UIEvent.SHOW , false, false );
			_uiActionSheet.dispatchEvent( uiEvent );
			
			uiActionSheet.invalidateDisplayList();
			_uiActionSheetBitmap = getCaptureedUIActionSheet( uiActionSheet );
			_uiActionSheetBitmap.y = s.stageHeight;
			
			s.addChild( _uiActionSheetBitmap );
			
			tabBar = Navigator.getInstance().tabBar;
			targetY = ( s.stageHeight-uiActionSheet.viewHeight );
			
			// 만약 탭바가 활성화되어 있다면, targetY 를 탭바영역만큼 더 위로 올려준다.
//			if( tabBar && s.contains( tabBar ) )
//			{
//				targetY -= tabBar.viewHeight;
//			}
			
			TweenLite.to( _uiActionSheetBitmap, 0.5, {y:targetY, 
				ease:Quint.easeOut, 
				onComplete : onShowInViewComplete } );
		}
	
		
		/**
		 * @param uiActionSheet : UIActionSheet - 하단에서 사라질 액션 시트 객체.
		 */		
		public function hideInView():void
		{
			_isShow = false;
			
			if( _uiActionSheet )
			{
				var s : Stage = StageManager.getInstance().stage,
					targetY : Number;
				
				// 딤이 있으면 함께 제거.
				if( _modalWindow && s.contains( _modalWindow ) )
				{
					removeModal();
				}
				
				// 캡쳐본을 저장해두고,
				if( _uiActionSheetBitmap == null )
				{
					_uiActionSheetBitmap = getCaptureedUIActionSheet( _uiActionSheet );
					_uiActionSheetBitmap.y = _uiActionSheet.y;
					s.addChild( _uiActionSheetBitmap );
				}
				else
				{
					TweenLite.killTweensOf( _uiActionSheetBitmap );
				}
				
				var uiEvent : UIEvent = new UIEvent( UIEvent.HIDE , false, false );
				_uiActionSheet.dispatchEvent( uiEvent );
				
				// 화면에 붙은 실제 액션시트를 제거한다.
				if( s.contains( _uiActionSheet ) ) s.removeChild( _uiActionSheet );
				if( _dicAutoDestroy[ _uiActionSheet ] ) _uiActionSheet.destroy();
				
				delete _dicAutoDestroy[ _uiActionSheet ];
				_uiActionSheet = null;
				
				TweenLite.to( _uiActionSheetBitmap, 0.5, {y:( s.stageHeight ), 
					ease:Quint.easeOut, onComplete:onHideComplete} );
				
				
			}
		}
		
		
		
		/**
		 * <br>모달윈도우가 없으면 새로 생성하고,</br>
		 * <br>기본셋팅을 하며, stage 의 Resize 이벤트에 대응한다. </br>
		 * <br>modal이 remove 될때 이벤트 제거.</br>
		 */		
		public function addModal():void
		{
			var s : Stage = StageManager.getInstance().stage;
			
			if( _modalWindow == null )
			{
				var g : Graphics;
				_modalWindow = new Sprite();
				g = _modalWindow.graphics;
				g.beginFill( 0x000000, 1 );
				g.drawRect( 0, 0, s.stageWidth,s.stageHeight );
				g.endFill();
				
				_modalWindow.alpha = 0.5;
				
				_modalWindow.addEventListener(MouseEvent.CLICK, onModalClick );
				
			}
			else if( s.contains( _modalWindow ) )
			{
				return;
			}
			
			s.addChild( _modalWindow );
			s.addEventListener(Event.RESIZE, onStageResize );
		}
		
		
		/**
		 * 모달윈도우를 stage에서 제거하고, 리사이즈 이벤트를 제거한다.
		 */		
		public function removeModal():void
		{
			var s : Stage = StageManager.getInstance().stage;
			if( _modalWindow && s.contains( _modalWindow ) ) s.removeChild( _modalWindow ); 
			s.removeEventListener(Event.RESIZE, onStageResize );
		}
		
		//-----------------------------------------------------------------------------------
		// setter / getter
		//-----------------------------------------------------------------------------------
		
		/**
		 * 팝업 띄울때 생기는 Dimed : Sprite
		 * @param value
		 */		
		public function set modalWindow(value:Sprite):void
		{
			
			var isModalAdded : Boolean = false,
				parent : DisplayObjectContainer;
			if( _modalWindow && _modalWindow.parent )
			{
				isModalAdded = true;
				parent = _modalWindow.parent;
				_modalWindow.parent.removeChild( _modalWindow );
				_modalWindow.removeEventListener(MouseEvent.CLICK, onModalClick );
			}
			
			_modalWindow = value;
			_modalWindow.addEventListener(MouseEvent.CLICK, onModalClick );
			if( isModalAdded ) parent.addChild( _modalWindow );
			
		}
		
		//-----------------------------------------------------------------------------------
		// protected functions
		//-----------------------------------------------------------------------------------
		
		
		
		//-----------------------------------------------------------------------------------
		// internal functions
		//-----------------------------------------------------------------------------------
		
		
		
		
		//-----------------------------------------------------------------------------------
		// private functions
		//-----------------------------------------------------------------------------------
		
		private function onShowInViewComplete():void
		{
			if( _isShow == false ||  _uiActionSheet == null || _uiActionSheetBitmap == null ) return;
			
			var s : Stage;
			s = StageManager.getInstance().stage;
			
			// 실제 객체를 붙이고
			if( _uiActionSheet )
			{
				_uiActionSheet.y = _uiActionSheetBitmap.y;
				s.addChild( _uiActionSheet );
			}
			
			// 비트맵 제거
			if( _uiActionSheetBitmap && s.contains( _uiActionSheetBitmap ) ) s.removeChild( _uiActionSheetBitmap );
			_uiActionSheetBitmap = null;
		}
		
		// 사라지는 모션 완료시.
		private function onHideComplete():void
		{
			if( _isShow ) return;
			
			var s : Stage;
			s = StageManager.getInstance().stage;
			
			// 비트맵 제거
			if( _uiActionSheetBitmap && s.contains( _uiActionSheetBitmap ) ) s.removeChild( _uiActionSheetBitmap );
			_uiActionSheetBitmap = null;
		}
		
		// UIActionSheet 캡처해서 Bitmap 반환
		private function getCaptureedUIActionSheet( uiActionSheet : UIActionSheet ):Bitmap
		{
			var bd : BitmapData, bm : Bitmap, s : Stage;
			
			s = StageManager.getInstance().stage;
			
			bd = new BitmapData( s.stageWidth,s.stageHeight, true, 0x000000 );
			bd.draw( uiActionSheet );
			
			return new Bitmap( bd );
		}
		
		//-----------------------------------------------------------------------------------
		// event handler
		//-----------------------------------------------------------------------------------
		
		/**
		 * Dimed 영역이 클릭되면 팝업을 제거한다.
		 * @param e
		 */		
		protected function onModalClick(e:MouseEvent):void
		{
			hideInView();
			removeModal();
		}
		
		
		/**
		 * @param e
		 */		
		protected function onStageResize(e:Event):void
		{
			var s : Stage = StageManager.getInstance().stage;
			if( _modalWindow && _modalWindow.parent )
			{
				_modalWindow.width = s.stageWidth;
				_modalWindow.height = s.stageHeight;
			}
		}
	}
}






class singletonEnforce{}